package com.mtnz.njk.Service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.mtnz.njk.GexinUtil.PushToSingle;
import com.mtnz.njk.Mapper.*;
import com.mtnz.njk.entity.*;
import com.mtnz.njk.result.PageInfo;
import com.mtnz.njk.result.ResponseMessage;
import com.mtnz.njk.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/*
......................我佛慈悲......................
 *                       _oo0oo_
 *                      o8888888o
 *                      88" . "88
 *                      (| -_- |)
 *                      0\  =  /0
 *                    ___/`---'\___
 *                  .' \\|     |// '.
 *                 / \\|||  :  |||// \
 *                / _||||| -卍-|||||- \
 *               |   | \\\  -  /// |   |
 *               | \_|  ''\---/''  |_/ |
 *               \  .-\__  '-'  ___/-. /
 *             ___'. .'  /--.--\  `. .'___
 *          ."" '<  `.___\_<|>_/___.' >' "".
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *         \  \ `_.   \_ __\ /__ _/   .-` /  /
 *     =====`-.____`.___ \_____/___.-`___.-'=====
 *                       `=---='
 *
 *..................佛祖开光 ,永无BUG...................
 */

/**
 * @Description: 帖子评论相关业务层
 * @Author: ZPX
 * @CreateDate: 2019/7/18 10:03
 * @Version: 1.0
 */
@Service
public class CommentResearchService {

    //评论
    @Autowired
    CommentResearchMapper commentResearchMapper;

    //评论图
    @Autowired
    CommentResearchImgMapper commentResearchImgMapper;

    //用户
    @Autowired
    CommunityUserMapper communityUserMapper;

    //用户扩展
    @Autowired
    CommunityUserInfoMapper communityUserInfoMapper;

    //评论点赞
    @Autowired
    PraiseCommentResearchMapper praiseCommentResearchMapper;

    //用户任务
    @Autowired
    UserTaskMapperr userTaskMapperr;

    @Autowired
    UserTaskCountMapper userTaskCountMapper;

    @Autowired
    CountCommunityMapper countCommunityMapper;

    //帖子
    @Autowired
    ResearchMapper researchMapper;

    //消息
    @Autowired
    NewsMapper newsMapper;

    @Autowired
    ResearchBannerMapper researchBannerMapper;

    /**
     * 研究院发布评论
     *
     * @param researchId
     * @param userId
     * @param message
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult saveCommentResearch(String researchId, String userId, String message, String img) throws Exception {

        // 根据userId查询comment_research表最近的date
        String commentResearchByUserid = commentResearchMapper.findCommentResearchByUserid(userId);
        // 该用户必须评论过
        if (commentResearchByUserid != null && commentResearchByUserid.length() > 0) {
            // 得到最近的一次评论的时间
            Date date = DateUtil.parse(commentResearchByUserid);
            Date date1 = DateUtil.date(System.currentTimeMillis());
            // 与当前时间相比较
            long interval = (date1.getTime() - date.getTime()) / 1000;
            // 如果小于10秒，不允许用户继续操作
            if (interval < 10) {
                return new ResponseResult(ResponseMessage.FREQUENT_FEEDBACK);
            }
        }
        Example example1 = new Example(NjkUserEntity.class);
        example1.createCriteria().andEqualTo("userId", userId);
        List<NjkUserEntity> njkUserEntities = communityUserMapper.selectByExample(example1);

        //调用积分方法
        String inform = IntegralService(userId, researchId, message, njkUserEntities);

        //保存评论相关信息
        CommentResearchImgEntity commentResearchImgEntity = new CommentResearchImgEntity();
        for (NjkUserEntity njkUserEntity : njkUserEntities) {
            Example example2 = new Example(ResearchEntity.class);
            example2.createCriteria().andEqualTo("researchId", researchId);
            List<ResearchEntity> researchEntities = researchMapper.selectByExample(example2);
            for (ResearchEntity researchEntity : researchEntities) {
                researchEntity.setCreateTime(DateUtil.now());
                researchEntity.setRecover(researchEntity.getRecover() + 1);
                researchMapper.updateByPrimaryKey(researchEntity);
                //发送消息
                NewsEntity newsEntity = new NewsEntity();
                newsEntity.setNewsId(IdUtil.simpleUUID());
                newsEntity.setId(researchEntity.getResearchId().toString());
                newsEntity.setMessage(message);
                newsEntity.setName(njkUserEntity.getNickName());
                newsEntity.setImg(njkUserEntity.getImg());
                newsEntity.setCreateDate(DateUtil.now());
                newsEntity.setUserId(researchEntity.getUserId());
                newsEntity.setSubject(researchEntity.getSubject());
                newsEntity.setStatus("8");
                newsEntity.setUserId1(researchEntity.getUserId());
                newsMapper.insert(newsEntity);
                njkUserEntity.setStatus("1");
                communityUserMapper.updateByPrimaryKey(njkUserEntity);
                //推送
                ResearchEntity researchEntity1 = researchMapper.selectByPrimaryKey(researchId);
                NjkUserEntity njkUserEntitys = communityUserMapper.selectByPrimaryKey(researchEntity1.getUserId());
                PushToSingle pushToSingle = new PushToSingle();
                pushToSingle.pushToSingle(njkUserEntitys.getClientId(),"","",2,"xxxx",2);
            }
        }

        //保存评论
        CommentResearchEntity commentResearchEntitys = new CommentResearchEntity();
        commentResearchEntitys.setResearchId(Integer.parseInt(researchId));
        commentResearchEntitys.setUserId(userId);
        commentResearchEntitys.setName("");
        commentResearchEntitys.setReplyId("");
        commentResearchEntitys.setReplyName("");
        commentResearchEntitys.setPid("");
        commentResearchEntitys.setExamine("");
        commentResearchEntitys.setMessage(message);
        commentResearchEntitys.setCreateDate(DateUtil.now());
        commentResearchEntitys.setStatus("0");
        commentResearchEntitys.setViews(0);
        commentResearchEntitys.setMonth(DateUtil.today());
        commentResearchMapper.insert(commentResearchEntitys);

        Integer byCreateDate = commentResearchMapper.findByCreateDate(researchId);
        Integer commentResearchId = Integer.valueOf(byCreateDate);
        //保存图片
        if (img != null && img != "" && !"".equals(img)) {
            String[] split = img.split(",");
            List<String> strings = Arrays.asList(split);
            for (String string : strings) {
                commentResearchImgEntity.setCommentResearchId(commentResearchId);
                commentResearchImgEntity.setCreateDate(DateUtil.date());
                commentResearchImgEntity.setImg(string);
                commentResearchImgMapper.insert(commentResearchImgEntity);
            }
        }

        return new ResponseResult(ResponseMessage.OK, inform);
    }

    /**
     * 回复评论
     *
     * @param userId
     * @param researchId
     * @param message
     * @param commentResearchId
     * @return
     */
    @Transactional
    public ResponseResult commentResearchReply(String userId, String researchId, String message, String commentResearchId) throws Exception {
        CommentResearchEntity commentResearchEntity = new CommentResearchEntity();
        //获取用户数据
        Example example = new Example(NjkUserEntity.class);
        example.createCriteria().andEqualTo("userId", userId);
        List<NjkUserEntity> njkUserEntities = communityUserMapper.selectByExample(example);
        //获取回复表数据
        CommentResearchEntity commentResearchEntitys = commentResearchMapper.selectByPrimaryKey(commentResearchId);
        //保存回复
        commentResearchEntity.setUserId(userId);
        commentResearchEntity.setName("");
        commentResearchEntity.setResearchId(Integer.parseInt(researchId));
        commentResearchEntity.setReplyId("");
        commentResearchEntity.setReplyName("");
        commentResearchEntity.setMessage(message);
        commentResearchEntity.setCreateDate(DateUtil.now());
        commentResearchEntity.setStatus("1");
        commentResearchEntity.setMonth(DateUtil.today());
        commentResearchEntity.setPid(commentResearchId);
        commentResearchEntity.setViews(0);
        commentResearchEntity.setExamine("");
        commentResearchMapper.insert(commentResearchEntity);
        //更新时间
        ResearchEntity researchEntity = researchMapper.selectByPrimaryKey(researchId);
        researchEntity.setCreateTime(DateUtil.now());
        researchMapper.updateByPrimaryKey(researchEntity);
        //发送消息
        for (NjkUserEntity njkUserEntity : njkUserEntities) {
            NewsEntity newsEntity = new NewsEntity();
            newsEntity.setNewsId(IdUtil.simpleUUID());
            newsEntity.setId(researchEntity.getResearchId().toString());
            newsEntity.setMessage(message);
            newsEntity.setName(njkUserEntity.getNickName());
            newsEntity.setImg(njkUserEntity.getImg());
            newsEntity.setCreateDate(DateUtil.now());
            newsEntity.setUserId(commentResearchEntitys.getUserId());
            newsEntity.setSubject(researchEntity.getSubject());
            newsEntity.setStatus("8");
            newsEntity.setUserId1(researchEntity.getUserId());
            newsEntity.setUrl("");
            newsMapper.insert(newsEntity);
            njkUserEntity.setStatus("1");
            communityUserMapper.updateByPrimaryKey(njkUserEntity);
            //推送
            ResearchEntity researchEntity1 = researchMapper.selectByPrimaryKey(researchId);
            NjkUserEntity njkUserEntitys = communityUserMapper.selectByPrimaryKey(researchEntity1.getUserId());
            PushToSingle pushToSingle = new PushToSingle();
            pushToSingle.pushToSingle(njkUserEntitys.getClientId(),"","",2,"xxxx",2);
        }
        //调用积分方法
        String inform = IntegralService(userId, researchId, message, njkUserEntities);
        return new ResponseResult(ResponseMessage.OK, inform);
    }


    /**
     * 回复评论回复
     *
     * @param researchId 研究院
     * @param userId     用户
     * @param message    内容
     * @param pid        上一条回复的ID
     * @return
     */
    @Transactional
    public ResponseResult commentResearchReplys(String userId, String researchId, String message, String replyId, String pid) throws Exception {
        //获取用户数据
        Example example = new Example(NjkUserEntity.class);
        example.createCriteria().andEqualTo("userId", userId);
        List<NjkUserEntity> njkUserEntities = communityUserMapper.selectByExample(example);
        //保存回复
        CommentResearchEntity commentResearchEntitys = new CommentResearchEntity();
        commentResearchEntitys.setResearchId(Integer.parseInt(researchId));
        commentResearchEntitys.setUserId(userId);
        commentResearchEntitys.setMessage(message);
        commentResearchEntitys.setName("");
        commentResearchEntitys.setReplyId(replyId);
        commentResearchEntitys.setReplyName("");
        commentResearchEntitys.setCreateDate(DateUtil.now());
        commentResearchEntitys.setStatus("1");
        commentResearchEntitys.setMonth(DateUtil.today());
        commentResearchEntitys.setViews(0);
        commentResearchEntitys.setExamine("");
        commentResearchEntitys.setPid(pid);
        commentResearchMapper.insert(commentResearchEntitys);
        //更新时间
        ResearchEntity researchEntity = researchMapper.selectByPrimaryKey(researchId);
        if (researchEntity!=null){
        researchEntity.setCreateTime(DateUtil.now());
        }
        researchMapper.updateByPrimaryKey(researchEntity);

        //发送消息
        for (NjkUserEntity njkUserEntity : njkUserEntities) {
            NewsEntity newsEntity = new NewsEntity();
            newsEntity.setNewsId(IdUtil.simpleUUID());
            newsEntity.setId(researchEntity.getResearchId().toString());
            newsEntity.setMessage(message);
            newsEntity.setName(njkUserEntity.getNickName());
            newsEntity.setImg(njkUserEntity.getImg());
            newsEntity.setCreateDate(DateUtil.now());
            newsEntity.setUserId(replyId);
            newsEntity.setSubject(researchEntity.getSubject());
            newsEntity.setStatus("8");
            newsEntity.setUserId1(researchEntity.getUserId());
            newsMapper.insert(newsEntity);
            njkUserEntity.setStatus("1");
            communityUserMapper.updateByPrimaryKey(njkUserEntity);
            //推送
            ResearchEntity researchEntity1 = researchMapper.selectByPrimaryKey(researchId);
            NjkUserEntity njkUserEntitys = communityUserMapper.selectByPrimaryKey(researchEntity1.getUserId());
            PushToSingle pushToSingle = new PushToSingle();
            pushToSingle.pushToSingle(njkUserEntitys.getClientId(),"","",2,"xxxx",2);
        }
        //判断评论内容不为空并且大于3
        String inform = IntegralService(userId, researchId, message, njkUserEntities);
        return new ResponseResult(ResponseMessage.OK, inform);
    }


    /**
     * 商品研究社帖子详情下评论列表
     *
     * @param researchId
     * @return
     * @throws Exception
     */
    public ResponseResult findComment(Integer researchId, String userId, Integer pageNum, Integer pageSize) throws Exception {
        //分页
        PageHelper.startPage(pageNum, pageSize);
        //获取帖子评论信息
        Example example = new Example(CommentResearchEntity.class);
        example.createCriteria().andEqualTo("status", 0).andEqualTo("researchId", researchId);

        List<CommentResearchEntity> commentResearchEntities = commentResearchMapper.selectByExample(example);

        commentResearchEntities.stream().forEach(e -> {
            //获取评论图
            List<CommentResearchImgEntity> commentResearchImgEntities = commentResearchImgMapper.showCommentResearchImg(e.getCommentResearchId().toString());
            if (commentResearchImgEntities.size() != 0) {
                e.setCommentResearchImgEntities(commentResearchImgEntities);
            }
            //查询是否点过赞
            if (userId != null && !userId.equals("")) {
                PraiseCommentResearchEntity praiseCommentResearchEntity = praiseCommentResearchMapper.showPraiseCommentStatus(e.getCommentResearchId().toString(), userId);
                if (praiseCommentResearchEntity != null) {
                    e.setZan("1");
                } else {
                    e.setZan("0");
                }
            }
            //获取回复
            Example example5 = new Example(CommentResearchEntity.class);
            example5.setOrderByClause("create_date ASC");
            example5.createCriteria().andEqualTo("status", 1).andEqualTo("pid", e.getCommentResearchId());
            List<CommentResearchEntity> commentResearchEntities1 = commentResearchMapper.selectByExample(example5);
            e.setComment(commentResearchEntities1);
            for (CommentResearchEntity commentResearchEntity : commentResearchEntities1) {
                //获取评论人姓名
                Example example1 = new Example(NjkUserEntity.class);
                example1.createCriteria().andEqualTo("userId", commentResearchEntity.getUserId());
                List<NjkUserEntity> njkUserEntities = communityUserMapper.selectByExample(example1);
                for (NjkUserEntity njkUserEntity : njkUserEntities) {
                    String name = njkUserEntity.getNickName();
                    commentResearchEntity.setNickName(name);
                }

                //获取回复人姓名
                Example example2 = new Example(NjkUserEntity.class);
                example2.createCriteria().andEqualTo("userId", commentResearchEntity.getReplyId());
                List<NjkUserEntity> njkUserEntities1 = communityUserMapper.selectByExample(example2);
                for (NjkUserEntity njkUserEntity : njkUserEntities1) {
                    String name = njkUserEntity.getNickName();
                    commentResearchEntity.setPName(name);
                }

                //获取用户头像
                Example example3 = new Example(NjkUserInfoEntity.class);
                example3.createCriteria().andEqualTo("userId", commentResearchEntity.getUserId());
                List<NjkUserInfoEntity> njkUserInfoEntities = communityUserInfoMapper.selectByExample(example3);
                for (NjkUserInfoEntity njkUserInfoEntity : njkUserInfoEntities) {
                    String img = njkUserInfoEntity.getImg();
                    commentResearchEntity.setImg(img);
                }
            }

            //获取评论人姓名
            Example example1 = new Example(NjkUserEntity.class);
            example1.createCriteria().andEqualTo("userId", e.getUserId());
            List<NjkUserEntity> njkUserEntities = communityUserMapper.selectByExample(example1);
            for (NjkUserEntity njkUserEntity : njkUserEntities) {
                String name = njkUserEntity.getNickName();
                e.setNickName(name);
            }

            //获取回复人姓名
            Example example2 = new Example(NjkUserEntity.class);
            example2.createCriteria().andEqualTo("userId", e.getReplyId());
            List<NjkUserEntity> njkUserEntities1 = communityUserMapper.selectByExample(example2);
            for (NjkUserEntity njkUserEntity : njkUserEntities1) {
                String name = njkUserEntity.getNickName();
                e.setPName(name);
            }

            //获取用户头像
            Example example3 = new Example(NjkUserInfoEntity.class);
            example3.createCriteria().andEqualTo("userId", e.getUserId());
            List<NjkUserInfoEntity> njkUserInfoEntities = communityUserInfoMapper.selectByExample(example3);
            for (NjkUserInfoEntity njkUserInfoEntity : njkUserInfoEntities) {
                String img = njkUserInfoEntity.getImg();
                e.setImg(img);
            }
        });

        PageInfo pageInfo = new PageInfo<>(commentResearchEntities);

        return new ResponseResult(ResponseMessage.OK, pageInfo);
    }

    /**
     * 研究院评论点赞
     *
     * @param commentResearchId
     * @param userId
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult praiseCommentResearch(Integer commentResearchId, String userId) throws Exception {
        CommentResearchEntity commentResearchEntity = commentResearchMapper.selectByPrimaryKey(commentResearchId);
        //封装结果集
        Map map = new HashMap<>();
        String praiseStatus = "";
        //查询是否有该用户对该评论的点赞记录
        Example example = new Example(PraiseCommentResearchEntity.class);
        example.createCriteria().andEqualTo("commentResearchId", commentResearchId)
                .andEqualTo("userId", userId);
        List<PraiseCommentResearchEntity> praiseCommentResearchEntities = praiseCommentResearchMapper.selectByExample(example);
        if (praiseCommentResearchEntities != null && praiseCommentResearchEntities.size() > 0) {

            //如果找到了这条记录，则删除该记录，同时文章的点赞数减1
            PraiseCommentResearchEntity praiseCommentResearchEntity = praiseCommentResearchEntities.get(0);
            praiseCommentResearchEntity.getCommentResearchId();
            praiseCommentResearchEntity.getUserId();
            //删除记录
            praiseCommentResearchMapper.deletePraiseCommentResearch(praiseCommentResearchEntity);

            //评论点赞数减1，查询时使用Mysql行级锁解决并发覆盖问题
            if (commentResearchEntity.getViews()>0) {
                commentResearchEntity.setViews(commentResearchEntity.getViews() - 1);
                commentResearchMapper.updateByPrimaryKey(commentResearchEntity);
            }
            praiseStatus = "0";
        } else {
            PraiseCommentResearchEntity praiseCommentResearchEntity = new PraiseCommentResearchEntity();
            //如果没有找到这条记录，则添加这条记录，同时评论点赞数加1
            praiseCommentResearchEntity.setCommentResearchId(commentResearchId);
            praiseCommentResearchEntity.setUserId(userId);
            //添加记录
            praiseCommentResearchMapper.insert(praiseCommentResearchEntity);

            //评论点赞数加1，查询时使用Mysql行级锁解决并发覆盖问题
            commentResearchEntity.setViews(commentResearchEntity.getViews() + 1);
            commentResearchMapper.updateByPrimaryKey(commentResearchEntity);
            praiseStatus = "1";
        }
        map.put("praiseStatus", praiseStatus);
        map.put("views", commentResearchEntity.getViews());
        return new ResponseResult(ResponseMessage.OK, map);
    }


    /**
     * 查询社区首页轮播图
     *
     * @return
     * @throws Exception
     */
    public ResponseResult listResearchBanner() throws Exception {
        List<ResearchBannerEntity> researchBannerEntities = researchBannerMapper.selectAll();
        return new ResponseResult(ResponseMessage.OK,researchBannerEntities);
    }


    /**
     * 封装积分操作
     *
     * @param userId
     * @param researchId
     * @param message
     * @param njkUserEntities
     */
    private String IntegralService(String userId, String researchId, String message, List<NjkUserEntity> njkUserEntities) {
        String inform;
        if (message != null && message.length() > 3) {
            Example example2 = new Example(UserTaskEntity.class);
            example2.createCriteria().andEqualTo("userId", userId);
            List<UserTaskEntity> userTaskEntities = userTaskMapperr.selectByExample(example2);
            if (userTaskEntities != null && userTaskEntities.size() > 0) {
                for (UserTaskEntity userTaskEntity : userTaskEntities) {
                    Integer.parseInt(userTaskEntity.getResearchStatus().toString());
                    Integer researchNum = Integer.parseInt(userTaskEntity.getResearchNum().toString()) + 1;
                    CountCommunityEntity countCommunityEntity = new CountCommunityEntity();
                    //判断今天是否已完成 任务
                    if (researchNum <= 15) {
                        //添加到社区类型
                        countCommunityEntity.setCommunityType(1);
                        countCommunityEntity.setCreateTime(DateUtil.date());
                        countCommunityEntity.setUserId(userId);
                        countCommunityEntity.setNum("1");
                        countCommunityEntity.setCommunityId(researchId);
                        countCommunityEntity.setNews("评论研究院帖子");
                        countCommunityEntity.setOrderNum("");
                        countCommunityEntity.setAudit(0);
                        countCommunityMapper.insert(countCommunityEntity);
                        //增加积分
                        for (NjkUserEntity njkUserEntity : njkUserEntities) {
                            njkUserEntity.setIntegral(njkUserEntity.getIntegral() + 1);
                            //增加总积分
                            njkUserEntity.setTotalIntegral(njkUserEntity.getTotalIntegral() + 1);
                            communityUserMapper.updateByPrimaryKey(njkUserEntity);
                        }
                        //添加用户任务
                        userTaskEntity.setUserId(userId);
                        userTaskEntity.setResearchNum(researchNum);
                        userTaskEntity.setResearchStatus(1);
                        userTaskMapperr.updateByPrimaryKey(userTaskEntity);
                        //添加单个任务
                        UserTaskCountEntity userTaskCountEntity = new UserTaskCountEntity();
                        userTaskCountEntity.setUserId(userId);
                        userTaskCountEntity.setTaskType(4);
                        userTaskCountEntity.setCreateTime(DateUtil.date());
                        userTaskCountMapper.insert(userTaskCountEntity);

                    }
                }
            }
        }
        return inform = "1";
    }
}

